import React, { useEffect } from 'react'
import { useEffectOnce } from '@/utils/hooks'
import './index.scss'

const RoomUsers = ({
  userId,
  onSelectUserId,
  selectUserId,
  roomInfo,
}) => {

  useEffectOnce(() => {
    setTimeout(() => {
      onSelectUserId(userId)
    }, 500)
  })

  useEffect(() => {
    roomInfo.users.forEach(user => {
      const video = document.querySelector(`#user-view-${ user.id } video`)

      if (!video || !window.userStreamMap[ user.id ]) {
        return true
      }
      video.srcObject = window.userStreamMap[ user.id ]
      /* 自身需要静音 */
      if (user.id === userId) {
        video.muted = true
      }
    })
    onSelectUserId(selectUserId)
  }, [roomInfo])

  const showVideo = (user) => window.userStreamMap[ user.id ] && window.userStreamMap[ user.id ].getVideoTracks()[ 0 ].enabled

  return (
    <div className="room-users">
      {roomInfo.users.map((user, i) => (
        <div
          className={`user ${ selectUserId === user.id ? 'active' : null }`}
          id={`user-view-${ user.id }`}
          key={user.id}
          onClick={() => onSelectUserId(user.id)}
        >
          {showVideo(user)
            ? (
              <video
                autoPlay
              />
            )
            : (
              <img
                alt=""
                src="https://aha-public-1301319986.cos.ap-shanghai.myqcloud.com/static_file/%E5%9B%BE%E6%A0%87/logo.png"
              />
            )}
          <div className="nickname">{user.nickname || `用户${ i }`}</div>
        </div>
      ))}
    </div>
  )
}

export default RoomUsers
